/**
 * Copyright © 2016-2021 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.iot.ruleNode;

import com.example.iot.msg.TbMsg;
import com.example.iot.script.ScriptEngine;
import lombok.extern.slf4j.Slf4j;

import static com.example.iot.util.DonAsynchron.withCallback;


@Slf4j
public class TbJsFilterNode implements TbNode {

    private TbJsFilterNodeConfiguration config;
    private ScriptEngine jsEngine;

    @Override
    public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
        this.config = TbNodeUtils.convert(configuration, TbJsFilterNodeConfiguration.class);
        this.jsEngine = ctx.createJsScriptEngine(config.getJsScript());
    }

    @Override
    public void onMsg(TbContext ctx, TbMsg msg) {
        withCallback(jsEngine.executeFilterAsync(msg),
                filterResult -> {
                    //ctx.logJsEvalResponse();
                    System.out.println("运行结果" + filterResult);
                    ctx.tellNext(msg, filterResult ? "True" : "False");
                },
                t -> {
                    System.out.println("运行结果" + t);
                    ctx.tellFailure(msg, t);
                    //ctx.logJsEvalFailure();
                }, ctx.getDbCallbackExecutor());
    }

    @Override
    public void destroy() {
        /*if (jsEngine != null) {
            jsEngine.destroy();
        }*/
    }
}
